package cn.yyx.common.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.DefaultCredentials;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.Bucket;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectResult;
import org.springframework.web.multipart.MultipartFile;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
public class OSSutils {
    //阿里云API的内或外网域名(https://help.aliyun.com/document_detail/31837.htm?spm=a2c4g.11186623.0.0.243d1cd54xAgEI#concept-zt4-cvy-5db)
    public static String ENDPOINT = "http://oss-cn-chengdu.aliyuncs.com";
    //阿里云API的密钥Access Key ID
//    public  static String ACCESS_KEY_ID="LTAI5tPZWvycQ4AZ9qfdJuGy";
//    //阿里云API的密钥Access Key Secret
//    public static String ACCESS_KEY_SECRET="xbBII1gWGS4dRxI3diIQYIpPdrPUaL";
    //阿里云API的bucket名称（空间名称）
    public static String BUCKET_NAME = "mbz-2302-1";
    //阿里云API的文件夹名称（空间中的文件夹名字）
    public static String FOLDER = "yyx-admin/";

    /**
     * 获得阿里云客户端对象
     *
     * @return
     */
    public static OSS getOSSClient() {
        OSS ossClient = null;
        try {
            EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
            DefaultCredentials defaultCredentials = new DefaultCredentials(System.getenv("OSS_ACCESS_KEY_ID"), System.getenv("OSS_ACCESS_KEY_SECRET"));
            credentialsProvider.setCredentials(defaultCredentials);
            ossClient = new OSSClientBuilder().build(ENDPOINT, credentialsProvider);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
//        return new OSSClient(ENDPOINT,ACCESS_KEY_ID,ACCESS_KEY_SECRET);
        return ossClient;
    }

    /**
     * 创建存储空间
     *
     * @param ossClient  阿里云客户端对象
     * @param bucketName 存储空间
     * @return
     */
    public static String createBucketName(OSSClient ossClient, String bucketName) {
        final String bucketNames = bucketName;
        if (ossClient.doesBucketExist(bucketNames)) {
            Bucket bucket = ossClient.createBucket(bucketNames);
            System.out.println("创建空间成功！");
            return bucket.getName();
        }
        return bucketNames;
    }

    /**
     * 删除存储空间
     *
     * @param ossClient
     * @param bucketName
     */
    public static void deleteBucketName(OSSClient ossClient, String bucketName) {
        ossClient.deleteBucket(bucketName);
        System.out.println("删除" + bucketName + "存储空间成功");
    }

    /**
     * 创建文件夹
     *
     * @param ossClient
     * @param bucketName
     * @param folder     文件夹名
     * @return 文件夹名
     */
    public static String creatFolder(OSSClient ossClient, String bucketName, String folder) {
        final String name = folder;
        if (!ossClient.doesObjectExist(bucketName, name)) {
//            不存在则创建文件夹
            ossClient.putObject(bucketName, name, new ByteArrayInputStream(new byte[0]));
            System.out.println("文件夹创建成功");
//            获取创建的文件夹名
            OSSObject object = ossClient.getObject(bucketName, name);
            String fileDir = object.getKey();
            return fileDir;
        }
        return name;
    }

    /**
     * 删除文件夹下的某个文件
     *
     * @param ossClient
     * @param bucketName
     * @param folder     文件夹名
     * @param fileName   文件名
     */
    public static void deleteFolder(OSSClient ossClient, String bucketName, String folder, String fileName) {
        ossClient.deleteObject(bucketName, folder + fileName);
        System.out.println("删除" + bucketName + "下的" + folder + fileName + "成功");
    }

    /**
     * 上传文件至OSS
     *
     * @param ossClient  oss客户端连接对象
     * @param file       上传文件（文件全路径如：D:\\image\\cake.jpg）
     * @param bucketName 存储空间
     * @param folder     模拟文件夹名 如"qj_nanjing/"
     * @return String 返回的唯一MD5数字签名
     */
    public static String uploadObject2OSS(OSS ossClient, MultipartFile file, String bucketName, String fileName, String folder) {
        String resultStr = null;
        try {
            //以输入流的形式上传文件
            InputStream is = file.getInputStream();
            //文件大小
            Long fileSize = file.getSize();
            if (fileSize > 0) {
                //创建上传Object的Metadata
                ObjectMetadata metadata = new ObjectMetadata();
                //上传的文件的长度
                metadata.setContentLength(is.available());
                //指定该Object被下载时的网页的缓存行为
                metadata.setCacheControl("no-cache");
                //指定该Object下设置Header
                metadata.setHeader("Pragma", "no-cache");
                //指定该Object被下载时的内容编码格式
                metadata.setContentEncoding("utf-8");
                //文件的MIME，定义文件的类型及网页编码，决定浏览器将以什么形式、什么编码读取文件。如果用户没有指定则根据Key或文件名的扩展名生成，
                //如果没有扩展名则填默认值application/octet-stream
                metadata.setContentType(getContentType(fileName));
                //指定该Object被下载时的名称（指示MINME用户代理如何显示附加的文件，打开或下载，及文件名称）
                metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
                //上传文件   (上传文件流的形式)
                PutObjectResult putResult = ossClient.putObject(bucketName, folder + fileName, is, metadata);
            }
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("上传阿里云OSS服务器异常." + e.getMessage());
        }
        //https://mbz-2302.oss-cn-chengdu.aliyuncs.com/images/3c3026d33cc84c0c86c69aba5448f24e.jpg
        return ("https://" + BUCKET_NAME + "." + ENDPOINT + "/" + FOLDER + fileName).replaceAll("http://", "");
    }

    /**
     * 通过文件名判断并获取OSS服务文件上传时文件的contentType
     *
     * @param fileName 文件名
     * @return 文件的contentType
     */
    public static String getContentType(String fileName) {
        //文件的后缀名
        String fileExtension = fileName.substring(fileName.lastIndexOf("."));
        if (".bmp".equalsIgnoreCase(fileExtension)) {
            return "image/bmp";
        }
        if (".gif".equalsIgnoreCase(fileExtension)) {
            return "image/gif";
        }
        if (".jpeg".equalsIgnoreCase(fileExtension) || ".jpg".equalsIgnoreCase(fileExtension) || ".png".equalsIgnoreCase(fileExtension)) {
            return "image/jpeg";
        }
        if (".html".equalsIgnoreCase(fileExtension)) {
            return "text/html";
        }
        if (".txt".equalsIgnoreCase(fileExtension)) {
            return "text/plain";
        }
        if (".vsd".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.visio";
        }
        if (".ppt".equalsIgnoreCase(fileExtension) || "pptx".equalsIgnoreCase(fileExtension)) {
            return "application/vnd.ms-powerpoint";
        }
        if (".doc".equalsIgnoreCase(fileExtension) || "docx".equalsIgnoreCase(fileExtension)) {
            return "application/msword";
        }
        if (".xml".equalsIgnoreCase(fileExtension)) {
            return "text/xml";
        }
        //默认返回类型
        return "image/jpeg";
    }
}
